/*
 * MinIO Cloud Storage (C) 2016, 2018 MinIO, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import React from "react"
import Select from 'react-select';
import axios from "axios"
import { connect } from "react-redux"
import Alert from "../alert/Alert"
import * as actionsAlert from "../alert/actions"
import InputGroup from "./InputGroup"
import RadioGroup from "./RadioGroup"
import Radio from "./Radio"
import web from "../web"
import { Redirect, Link } from "react-router-dom"
import history from "../history"
import storage from 'local-storage-fallback'
import AddAddressModal from "./AddAddressModal"

export class FileForm extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      showAddAddressModal: false,
      buckets: [],
      data2: [],
      // checkAddr: false,
      origin: "",
      username: "",
      step: "1",
      name: "test1",
      addr: "",
      // addr: "redis://:wf123456@master-node,127.0.0.1:16379,127.0.0.1:16380,127.0.0.1:16381",
      bucket: "",
      accessKey: "test",
      secretKey: "test",
      keyPath: "",
      // force: false,

      // addr2: "redis://:wf123456@master-node,127.0.0.1:16379,127.0.0.1:16380,127.0.0.1:16381",
      mp: "/jfs",
      gettimeout: "60",
      puttimeout: "60",
      maxuploads: "20",
      writeback: false,
      // prefetch: "1",
      buffersize: "300",
      cachedir: "/var/jfsCache",
      // cachesize: "1024",
      // freespaceratio: "0.1",
      cachepartialonly: false,
      // metrics: ":9567",
      nousagereport: false,
      nosyslog: false,
      background: false,
      // attrcache: "",
      // entrycache: "",
      // direntrycache: "",
      enablexattr: false,
    }
  }

  // Handle field changes
  formName(e) {
    this.setState({
      name: e.target.value
    })
  }

  formAddr(e) {
    this.setState({
      addr: e.target.value
    })
  }

  formBucket(e) {
    // console.log(e)
    this.setState({
      bucket: e.value
    })
    console.log(e.value)
  }
  formAccessKey(e) {
    this.setState({
      accessKey: e.target.value
    })
  }

  formSecretKey(e) {
    this.setState({
      secretKey: e.target.value
    })
  }
  formKeyPath(e) {
    this.setState({
      keyPath: e.target.value
    })
  }
  


  // formAddr2(e) {
  //   this.setState({
  //     addr2: e.target.value
  //   })
  // }
  formMp(e) {
    this.setState({
      mp: e.target.value
    })
  }
  formGetTimeout(e) {
    this.setState({
      gettimeout: e.target.value
    })
  }
  formPutTimeout(e) {
    this.setState({
      puttimeout: e.target.value
    })
  }
  formMaxUploads(e) {
    this.setState({
      maxuploads: e.target.value
    })
  }
  formWriteback(e) {
    this.setState({
      writeback: e
    })
  }
  // formPrefetch(e) {
  //   this.setState({
  //     prefetch: e.target.value
  //   })
  // }
  formBuffersize(e) {
    this.setState({
      buffersize: e.target.value
    })
  }
  formCachedir(e) {
    this.setState({
      cachedir: e.target.value
    })
  }
  // formCachesize(e) {
  //   this.setState({
  //     cachesize: e.target.value
  //   })
  // }
  // formFreespaceratio(e) {
  //   this.setState({
  //     freespaceratio: e.target.value
  //   })
  // }
  formCachepartialonly(e) {
    this.setState({
      cachepartialonly: e
    })
  }
  // formMetrics(e) {
  //   this.setState({
  //     metrics: e.target.value
  //   })
  // }
  formNousagereport(e) {
    this.setState({
      nousagereport: e
    })
  }
  formNosyslog(e) {
    this.setState({
      nosyslog: e
    })
  }
  // formBackground(e) {
  //   this.setState({
  //     background: e
  //   })
  // }
  // formAttrcache(e) {
  //   this.setState({
  //     attrcache: e.target.value
  //   })
  // }
  // formEntrycache(e) {
  //   this.setState({
  //     entrycache: e.target.value
  //   })
  // }
  // formDirentrycache(e) {
  //   this.setState({
  //     direntrycache: e.target.value
  //   })
  // }
  // formEnablexattr(e) {
  //   this.setState({
  //     enablexattr: e
  //   })
  // }

  showAddAddress(e) {
    e.preventDefault()
    this.setState({
      showAddAddressModal: true
    })
  }
  hideAddAddress() {
    this.setState({
      showAddAddressModal: false
    })
  }

  handleSubmitFormat(event) {
    event.preventDefault()
    const { showAlert, clearAlert } = this.props
    storage.setItem("addr",this.state.addr)
    console.log(this.state.addr)
    let message = ""
    // if (this.state.name === "") {
    //   message = "文件系统名称不能为空"
    // }
    // if (this.state.addr === "") {
    //   message = "地址不能为空"
    // }
    if (this.state.bucket === "") {
      message = "桶名称不能为空"
    }
    // if (this.state.accessKey === "") {
    //   message = "AccessKey不能为空"
    // }
    // if (this.state.secretKey === "") {
    //   message = "SecretKey不能为空"
    // }
    // if (this.state.blockSize === "") {
    //   message = "块大小不能为空"
    // }
    if (message) {
      showAlert("danger", message)
      return
    }
    axios({
      method: 'post',
      url: "http://"+window.location.hostname+":1323/format",
      headers: {'Content-Type': 'application/json','Access-Control-Allow-Origin':'*'},
      data: {
        username: this.state.username,
        name: this.state.name,
        addr: this.state.addr,
        storage: "minio",
        bucket: this.state.bucket,
        accessKey: this.state.accessKey,
        secretKey: this.state.secretKey,
        blockSize: "4096",
        compression: "lz4",
        keyPath: this.state.keyPath,
        force: false,
        shards: "0",
      }
    })
    .then(
      (response)=>{
        const { showAlert, clearAlert } = this.props
        let message = ""
        if (response.status == 200){
          // if (response.data =="format success"){
            message = response.data
            showAlert("success", message)
            this.setState({
              step: "2"
            })
          // }
        }
      }
    )
    .catch(
      (error)=>{
        console.log(error)
      }
    )
  }
  handleSubmitMount(event) {
    event.preventDefault()
    const { showAlert, clearAlert } = this.props
    storage.setItem("addr",this.state.addr)
    console.log(this.state.addr)
    let message = ""
    console.log(this.state.mp)
    if (this.state.mp == "") {
      message = "挂载目标目录不能为空"
    }
    if (message) {
      showAlert("danger", message)
      return
    }
    axios({
      method: 'post',
      url: "http://"+window.location.hostname+":1323/mount",
      headers: {'Content-Type': 'application/json','Access-Control-Allow-Origin':'*'},
      data: {
        "name": this.state.name,
        "username": this.state.username,
        "addr": this.state.addr,
        "mp": this.state.mp,
        "get-timeout": this.state.gettimeout,
        "put-timeout": this.state.puttimeout,
        "max-uploads": this.state.maxuploads,
        "writeback": this.state.writeback.toString(),
        "prefetch": "1",
        "buffer-size": this.state.buffersize,
        "cache-dir": this.state.cachedir,
        "cache-size": "1024",
        "free-space-ratio": "0.1",
        "cache-partial-only": this.state.cachepartialonly.toString(),
        "metrics": ":9567",
        "no-usage-report": this.state.nousagereport.toString(),
        "nosyslog": this.state.nosyslog.toString(),
        "background": this.state.background.toString(),
        "attr-cache": "1",
        "entry-cache": "1",
        "dir-entry-cache": "1",
        "enable-xattr": this.state.enablexattr.toString(),
      }
    })
    .then(
      (response)=>{
        const { showAlert, clearAlert} = this.props
        let message = ""
        if (response.status == 200){
          message = response.data
          showAlert("success", message)
          history.replace("/FileList")
          storage.setItem("logfilepath",this.state.mp)
          // alert(response.data)
          // if (response.data =="format success"){
          //   this.setState({
          //     step: "2"
          //   })
          // }
        }
      }
    )
    .catch(
      (error)=>{
        console.log(error)
      }
    )
  }
      

  componentDidUpdate() {
  }
  
  componentDidMount() {
    console.log('canmount FileForm============='+storage.getItem('canmount'))
    var origin = window.location.origin+'/'
    if(storage.getItem('canmount') == "true"){
      this.setState({
        step: "2"
      })
    }else{
      this.setState({
        step: "1"
      })
    }
    this.setState({
      username: storage.getItem('uname'),
      origin: origin,
      addr: "redis://"+storage.getItem('uname')+":"+storage.getItem('pwd')+"@master-node,"+window.location.hostname+":16379,"+window.location.hostname+":16380,"+window.location.hostname+":16381",
    })
    
    web.ListBuckets().then(res => {
      this.state.buckets = res.buckets ? res.buckets.map(bucket => bucket.name) : []
      this.state.buckets.map((value,index,arry)=>{
        this.state.data2.push({ 'value': this.state.origin + value, 'label': value })
      })
      console.log(this.state.data2)
      // console.log(this.state.origin + this.state.buckets[0])
      // this.setState({
      //   bucket: this.state.data2[0].value
      // })
      // this.formBucket(this.state.data2[0])
      // console.log(this.state.bucket)
    })
    .catch(
      (error)=>{
        console.log(error)
      }
    )

  }
  
  componentWillUnmount() {
    document.body.classList.remove("is-guest")
  } 

  step(x) {
    this.setState({
      step: x
    })
  }

  render() {
    const { clearAlert, alert } = this.props
    // if (web.LoggedIn()) {
    //   return <Redirect to={"/"} />
    // }
    let alertBox = <Alert {...alert} onDismiss={clearAlert} />
    // Make sure you don't show a fading out alert box on the initial web-page load.
    if (!alert.message) alertBox = ""
    const customStyles = {
      option: (provided, state) => ({
        ...provided,
        border: 'none',
        color: state.isSelected ? '#55bc8a' : '#4a5974',
        background: 'none'
      }),
      placeholder: provided => ({
        ...provided,
        fontSize: '12px',
        fontWeight: 'normal',
        color: '#757575',
      }),
    }
    return (
      <div className="file-form">
        {alertBox}
        
        {/* {(!this.state.checkAddr) && (
          <div className="file-wrap">
          <div className="step-banner">
            <div className="step-title">
              <h4>源数据服务器配置自动检测中……</h4>
            </div>
          </div>
        </div>
        )} */}
        {/* {(this.state.step == "1" && this.state.checkAddr) ? ( */}
        {this.state.step == "1" ? (
        <div className="file-wrap">
          <div className="step-banner">
            <div className="step-title">
              <div className="step-title-icon">
                <i className="fa fa-tags" />
              </div>
              <div className="step-title-content">
                <h3>文件系统创建</h3>
                <p>用户在此步骤创建一个文件存储空间。</p>
              </div>
            </div>
            <div className="step-container">
              <div className="step-div">
                <div className="step-num step-selected">
                  <span>文件系统创建</span>
                </div>
                <div className="step-num">
                  <span>传输属性设置</span>
                </div>
                <div className="step-num">
                  <span>挂载属性设置</span>
                </div>
                {/* <div className="step-num">
                  <span>第四步</span>
                </div> */}
              </div>
            </div>
          </div>
          <form className="step-form" onSubmit={this.handleSubmitFormat.bind(this)}>
            <div className="file-input">
              <InputGroup
                value={this.state.name}
                onChange={this.formName.bind(this)}
                label="文件系统名称"
                id="name"
                name="name"
                type="text"
                spellCheck="false"
                required="required"
                autoComplete="name"
                placeholder="名称"
                />
              {/* <InputGroup className="mr-40"
                value={this.state.addr}
                onChange={this.formAddr.bind(this)}
                label="源数据服务器配置"
                id="addr"
                name="addr"
                type="text"
                spellCheck="false"
                required="required"
                placeholder="addr"
                />
              <a className="add-addr" onClick={this.showAddAddress.bind(this)}>
                <i className="fas fa-plus" />
              </a>
              {this.state.showAddAddressModal && (
                <AddAddressModal
                  hideAddAddress={this.hideAddAddress.bind(this)}
                />
              )} */}
              {/* 改下拉列表，获取bucket的桶列表名 */}
              <div className="input-group text-l select-bucket">
                <label className="lg-label">桶名称</label>
                <Select
                  styles={customStyles}
                  options={this.state.data2}
                  onChange={this.formBucket.bind(this)}
                  theme={theme => ({
                    ...theme,
                    borderWidth: 1,
                    fontWeight:600,
                    colors: {
                      ...theme.colors,
                      primary25: '#EFF4F9',
                      primary: '#55bc8a',
                    },
                  })}
                />
              </div>
              <InputGroup
                value={this.state.accessKey}
                onChange={this.formAccessKey.bind(this)}
                label="AccessKey"
                id="accessKey"
                name="accessKey"
                type="text"
                spellCheck="false"
                required="required"
                placeholder="accessKey"
                />
              <InputGroup
                value={this.state.secretKey}
                onChange={this.formSecretKey.bind(this)}
                label="SecretKey"
                id="secretKey"
                name="password"
                type="password"
                spellCheck="false"
                required="required"
                placeholder="password"
                />
              <InputGroup
                value={this.state.keyPath}
                onChange={this.formKeyPath.bind(this)}
                label="RSA秘钥文件路径"
                id="keyPath"
                name="keyPath"
                type="text"
                spellCheck="false"
                required=""
                placeholder="RSA秘钥文件路径"
                />
              {/* <div className="input-group text-l">
                <label className="lg-label">强制</label>
                <RadioGroup onChange={this.formForce.bind(this)} active={this.state.force}>
                  <Radio value={true}>是</Radio>
                  <Radio value={false}>否</Radio>
                </RadioGroup>
              </div> */}
              <div className="step-btn">
                <button className="step-next" type="submit">
                  下一步
                </button>
              </div>
            </div>
          </form>
        </div>
        ):(
          
        <div className="file-wrap">
          <div className="step-banner">
            <div className="step-title">
              <div className="step-title-icon">
                <i className="fa fa-tags" />
              </div>
               {this.state.step == "2" && (
              <div className="step-title-content">
                <h3>传输属性设置</h3>
                <p>用户在此步骤设置上传/下载的相关配置信息。</p>
              </div>
              )}
              {this.state.step == "3" && (
              <div className="step-title-content">
                <h3>挂载属性设置</h3>
                <p>用户在此步骤设置文件挂载点/挂载目录配置信息。</p>
              </div>
              )}
              {/* {this.state.step == "4" && (
              <div className="step-title-content">
                <h3>第四步</h3>
                <p>xxxxxxxxxxxxxxx</p>
              </div>
              )} */}
            </div>
            <div className="step-container">
              <div className="step-div">
                <div className="step-num">
                  <span>文件系统创建</span>
                </div>
                {this.state.step == "2" ? (
                <div className="step-num step-selected">
                  <span>传输属性设置</span>
                </div>
                ):(
                <div className="step-num">
                  <span>传输属性设置</span>
                </div>
                )}
                {this.state.step == "3" ? (
                <div className="step-num step-selected">
                  <span>挂载属性设置</span>
                </div>
                ):(
                <div className="step-num">
                  <span>挂载属性设置</span>
                </div>
                )}
                {/* {this.state.step == "4" ? (
                <div className="step-num step-selected">
                  <span>第四步</span>
                </div>
                ):(
                <div className="step-num">
                  <span>第四步</span>
                </div>
                )} */}
              </div>
            </div>
          </div>
          <form className="step-form" onSubmit={this.handleSubmitMount.bind(this)}>
            {this.state.step == "2" && (
            <div className="file-input">
              {/* <InputGroup
                value={this.state.addr2}
                onChange={this.formAddr2.bind(this)}
                label="源数据服务器配置"
                id="addr2"
                name="addr2"
                type="text"
                spellCheck="false"
                required="required"
                placeholder="源数据服务器配置"
                /> */}
              <InputGroup
                value={this.state.gettimeout}
                onChange={this.formGetTimeout.bind(this)}
                label="下载最大等待时间"
                id="gettimeout"
                name="gettimeout"
                type="text"
                spellCheck="false"
                required="required"
                placeholder="下载最大等待时间"
                />
              <InputGroup
                value={this.state.puttimeout}
                onChange={this.formPutTimeout.bind(this)}
                label="上传最大等待时间"
                id="puttimeout"
                name="puttimeout"
                type="text"
                spellCheck="false"
                required="required"
                placeholder="上传最大等待时间"
                />
              <InputGroup
                value={this.state.maxuploads}
                onChange={this.formMaxUploads.bind(this)}
                label="最大并发请求数量"
                id="maxuploads"
                name="maxuploads"
                type="text"
                spellCheck="false"
                required="required"
                placeholder="最大并发请求数量"
                />
              <InputGroup
                value={this.state.buffersize}
                onChange={this.formBuffersize.bind(this)}
                label="缓冲区大小"
                id="buffersize"
                name="buffersize"
                type="text"
                spellCheck="false"
                required="required"
                placeholder="单位：MB"
                />
              <InputGroup
                value={this.state.cachedir}
                onChange={this.formCachedir.bind(this)}
                label="缓存目录"
                id="cachedir"
                name="cachedir"
                type="text"
                spellCheck="false"
                required="required"
                placeholder="缓存目录"
                />
              <div className="input-group text-l">
                <label className="lg-label">仅缓存随机读写</label>
                <RadioGroup onChange={this.formCachepartialonly.bind(this)} active={this.state.cachepartialonly}>
                  <Radio value={true}>是</Radio>
                  <Radio value={false}>否</Radio>
                </RadioGroup>
              </div>
              <div className="input-group text-l">
                <label className="lg-label">回写</label>
                <RadioGroup onChange={this.formWriteback.bind(this)} active={this.state.writeback}>
                  <Radio value={true}>是</Radio>
                  <Radio value={false}>否</Radio>
                </RadioGroup>
              </div>
              {/* <InputGroup
                value={this.state.prefetch}
                onChange={this.formPrefetch.bind(this)}
                label="预加载"
                id="prefetch"
                name="prefetch"
                type="text"
                spellCheck="false"
                required="required"
                placeholder="预加载"
                /> */}
              <div className="step-btn">
                {/* <a className="step-prev" onClick={() => {
                  this.setState({
                    step: "1"
                  })
                }}>
                  上一步
                </a> */}
                <a className="step-next" onClick={() => {
                  this.setState({
                    step: "3"
                  })
                  // clearAlert()
                }}>
                  下一步
                </a>
              </div>
            </div>
            )}
            {this.state.step == "3" && (
            <div className="file-input">
              <InputGroup
                value={this.state.mp}
                onChange={this.formMp.bind(this)}
                label="挂载目标目录"
                id="mp"
                name="mp"
                type="text"
                spellCheck="false"
                required="required"
                placeholder="挂载目标目录"
                />
              {/* <InputGroup
                value={this.state.cachesize}
                onChange={this.formCachesize.bind(this)}
                label="缓存大小"
                id="cachesize"
                name="cachesize"
                type="text"
                spellCheck="false"
                required="required"
                placeholder="缓存大小"
                /> */}
              {/* <InputGroup
                value={this.state.freespaceratio}
                onChange={this.formFreespaceratio.bind(this)}
                label="空闲空间比"
                id="freespaceratio"
                name="freespaceratio"
                type="text"
                spellCheck="false"
                required="required"
                placeholder="空闲空间比"
                /> */}
              {/* <InputGroup
                value={this.state.metrics}
                onChange={this.formMetrics.bind(this)}
                label="Metrics"
                id="metrics"
                name="metrics"
                type="text"
                spellCheck="false"
                required="required"
                placeholder="metrics"
                /> */}
              <div className="input-group text-l">
                <label className="lg-label">不发送使用情况报告</label>
                <RadioGroup onChange={this.formNousagereport.bind(this)} active={this.state.nousagereport}>
                  <Radio value={true}>是</Radio>
                  <Radio value={false}>否</Radio>
                </RadioGroup>
              </div>
              <div className="input-group text-l">
                <label className="lg-label">禁用系统日志</label>
                <RadioGroup onChange={this.formNosyslog.bind(this)} active={this.state.nosyslog}>
                  <Radio value={true}>是</Radio>
                  <Radio value={false}>否</Radio>
                </RadioGroup>
              </div>
              {/* <div className="input-group text-l">
                <label className="lg-label">后台运行</label>
                <RadioGroup onChange={this.formBackground.bind(this)} active={this.state.background}>
                  <Radio value={true}>是</Radio>
                  <Radio value={false}>否</Radio>
                </RadioGroup>
              </div>
              <div className="input-group text-l">
                <label className="lg-label">启动文件扩展属性（xattr）</label>
                <RadioGroup onChange={this.formEnablexattr.bind(this)} active={this.state.enablexattr}>
                  <Radio value={true}>是</Radio>
                  <Radio value={false}>否</Radio>
                </RadioGroup>
              </div> */}
              <div className="step-btn">
                <a className="step-prev" onClick={() => {
                  this.setState({
                    step: "2"
                  })
                }}>
                  上一步
                </a>
                <button className="step-next" type="submit">
                  完成
                </button>
              </div>
            </div>
            )}
            {/* {this.state.step == "4" && (
            <div className="file-input">
              <div className="input-group text-l">
                <label className="lg-label">禁用系统日志</label>
                <RadioGroup onChange={this.formNosyslog.bind(this)} active={this.state.nosyslog}>
                  <Radio value={true}>是</Radio>
                  <Radio value={false}>否</Radio>
                </RadioGroup>
              </div>
              <div className="input-group text-l">
                <label className="lg-label">后台运行</label>
                <RadioGroup onChange={this.formBackground.bind(this)} active={this.state.background}>
                  <Radio value={true}>是</Radio>
                  <Radio value={false}>否</Radio>
                </RadioGroup>
              </div> */}
              {/* <InputGroup
                value={this.state.attrcache}
                onChange={this.formAttrcache.bind(this)}
                label="Attrcache"
                id="attrcache"
                name="attrcache"
                type="text"
                spellCheck="false"
                required=""
                placeholder="attrcache"
                />
              <InputGroup
                value={this.state.entrycache}
                onChange={this.formEntrycache.bind(this)}
                label="Entrycache"
                id="entrycache"
                name="entrycache"
                type="text"
                spellCheck="false"
                required=""
                placeholder="entrycache"
                />
              <InputGroup
                value={this.state.direntrycache}
                onChange={this.formDirentrycache.bind(this)}
                label="Direntrycache"
                id="direntrycache"
                name="direntrycache"
                type="text"
                spellCheck="false"
                required=""
                placeholder="direntrycache"
                /> */}
                
              {/* <div className="input-group text-l">
                <label className="lg-label">启动文件扩展属性（xattr）</label>
                <RadioGroup onChange={this.formEnablexattr.bind(this)} active={this.state.enablexattr}>
                  <Radio value={true}>是</Radio>
                  <Radio value={false}>否</Radio>
                </RadioGroup>
              </div>
              
              <div className="step-btn">
                <a className="step-prev" onClick={() => {
                      this.setState({
                        step: "3"
                      })
                    }}>
                  上一步
                </a>
                <button className="step-next" type="submit">
                  完成
                </button>
              </div>
            </div>
            )} */}
          </form>
          </div>
        )}

      </div>
    )
  }
}

const mapDispatchToProps = dispatch => {
  return {
    showAlert: (type, message) =>
      dispatch(actionsAlert.set({ type: type, message: message })),
    clearAlert: () => dispatch(actionsAlert.clear())
  }
}

export default connect(
  state => state,
  mapDispatchToProps
)(FileForm)
